#include "formchildoperationlog.h"

#include <QTreeWidgetItem>
#include <QTableWidgetItem>
#include <QTreeWidget>
#include <QTableWidget>
#include <QPushButton>
#include <QHeaderView>
#include <QStringList>
#include <QDateTime>
#include <QHBoxLayout>
#include <QVBoxLayout>

#include <QDateEdit>
#include <QLineEdit>
#include <QLabel>
#include <QSqlQuery>
#include <QDebug>
#include "../database/dataauth.h"

const int nMaxVehNum = 300;
const int nMaxLogNum = 500;

// 运行日志类

OperationRunLog::OperationRunLog(QWidget *parent):QWidget(parent)
{
    m_logItemsVector.clear();

    m_pRunLogWin = new QTreeWidget;
    m_pRunLogWin->setRootIsDecorated(false);
    QStringList strHeadList;
    strHeadList << "时间" << "信息";
    m_pRunLogWin->setHeaderLabels(strHeadList);
    m_pRunLogWin->setColumnWidth(0, 100);

    QHBoxLayout *pMainLayout = new QHBoxLayout;
    pMainLayout->addWidget(m_pRunLogWin);
    pMainLayout->setMargin(0);
    this->setLayout(pMainLayout);
}

void OperationRunLog::slotRunLot(QString str)
{
    qDebug() << str;
    setRunLog(str);
}

void OperationRunLog::setRunLog(const QString &strLog)
{
    QTreeWidgetItem *pItem = new QTreeWidgetItem;
    pItem->setTextAlignment(0, Qt::AlignLeft);
    pItem->setTextAlignment(1, Qt::AlignLeft);
    pItem->setText(0, QDateTime::currentDateTime().toString("hh:mm:ss:zzz"));
    pItem->setText(1, strLog);

    if(m_logItemsVector.size() < nMaxLogNum)
    {
        m_logItemsVector.append(pItem);
        m_pRunLogWin->insertTopLevelItem(0, pItem);
    }
    else
    {
        QTreeWidgetItem *p = m_pRunLogWin->takeTopLevelItem(nMaxLogNum - 1);
        m_pRunLogWin->insertTopLevelItem(0, pItem);

        m_logItemsVector.removeFirst();
        m_logItemsVector.append(pItem);

        delete p;
        p=0;
    }
}
void OperationRunLog::clearRunLog()
{
    if(m_logItemsVector.size() > 0)
    {
        qDeleteAll(m_logItemsVector);
        m_pRunLogWin->clear();
        m_logItemsVector.clear();
    }
}

// 记录类
OperationRecord::OperationRecord(QStringList strHeadNameList,QWidget * parent) : QWidget(parent)
{
    m_strHeadNameList.clear();
    m_strHeadNameList = strHeadNameList;
    m_iRow = 0;

    createWin();
    setConnection();
}

void OperationRecord::createWin()
{
    m_pRecordTbl = new QTableWidget;

    m_pRecordTbl->verticalHeader()->hide();
    m_pRecordTbl->setEditTriggers(QAbstractItemView::NoEditTriggers);

    m_pRecordTbl->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_pRecordTbl->setSelectionMode(QAbstractItemView::SingleSelection);

    m_pRecordTbl->setColumnCount(m_strHeadNameList.size());

    m_pRecordTbl->setHorizontalHeaderLabels(m_strHeadNameList);

    for(int i = 0; i< m_strHeadNameList.size(); i++)
    {
        m_pRecordTbl->horizontalHeader()->setSectionResizeMode(i, QHeaderView::Stretch);
        m_pRecordTbl->horizontalHeaderItem(i)->setTextAlignment(Qt::AlignCenter);
    }

    QHBoxLayout * pMainLayout = new QHBoxLayout;
    pMainLayout->addWidget(m_pRecordTbl);
    pMainLayout->setMargin(0);

    this -> setLayout(pMainLayout);
}

void OperationRecord::setConnection()
{
    connect(m_pRecordTbl,SIGNAL(cellClicked(int,int)),this,SLOT(slotItemClicked(int,int)));
}

bool OperationRecord::comparePlateAndOwnner(int row,QString plate,QString ownner)
{
    if(row >= m_pRecordTbl->rowCount())
    {
        return false;
    }
    qDebug() << m_pRecordTbl->item(row,0)->text().trimmed();
    qDebug() << m_pRecordTbl->item(row,1)->text().trimmed();
    if(!QString::compare(plate,m_pRecordTbl->item(row,0)->text().trimmed())
            && !QString::compare(ownner,m_pRecordTbl->item(row,1)->text().trimmed()))
    {
        return true;
    }
    return false;
}

void OperationRecord::modifyRow(int row,QStringList strList)
{
    if(row >= m_pRecordTbl->rowCount())
    {
        return;
    }
    for(int i = 0; i < m_strHeadNameList.size();i++)
    {
        m_pRecordTbl->item(row, i)->setText(strList.at(i));
    }
}

bool OperationRecord::deleteRow(int row)
{
    QTableWidgetItem * pItem = NULL;
    for(int i = 0; i < m_strHeadNameList.size(); i++)
    {
        pItem = m_pRecordTbl->item(row,i);
        if(pItem)
        {
            delete pItem;
            pItem = NULL;
        }
    }
    m_pRecordTbl->removeRow(row);
    return true;
}

void OperationRecord::slotAddOneRow(QStringList strList)
{
    if(m_pRecordTbl->rowCount() >= nMaxVehNum)
    {
        QTableWidgetItem * pItem = NULL;
        for(int i = 0; i < m_strHeadNameList.size(); i++)
        {
            pItem = m_pRecordTbl->item(nMaxVehNum -1,i);
            if(pItem)
            {
                delete pItem;
                pItem = NULL;
            }
        }
        m_pRecordTbl->removeRow(nMaxVehNum - 1);
    }

    m_pRecordTbl->insertRow(0);
    for(int i = 0; i < m_strHeadNameList.size(); i++)
    {
        m_pRecordTbl->setItem(0, i, new QTableWidgetItem(strList.at(i)));
    }
    m_pRecordTbl->selectRow(0);
}

void OperationRecord::slotDelOneRow(QString plate,QString name)
{
      if(comparePlateAndOwnner(m_iRow,plate,name))
      {
          deleteRow(m_iRow);
      }
      else{
          for(int i = 0; i< m_pRecordTbl->rowCount(); i++)
          {
              if(comparePlateAndOwnner(i,plate,name))
              {
                 deleteRow(i);
                 return;
              }
          }
      }
}

void OperationRecord::slotModifyOneRow(QStringList strList)
{
    QString plate = strList.at(0); // 车牌
    QString name  = strList.at(1); // 车主姓名
    if(comparePlateAndOwnner(m_iRow,plate,name))
    {
        modifyRow(m_iRow,strList);
    }
    else{
        for(int i = 0; i< m_pRecordTbl->rowCount(); i++)
        {
            if(comparePlateAndOwnner(i,plate,name))
            {
               modifyRow(i,strList);
               return;
            }
        }
    }
}

void OperationRecord::slotClearAllRow()
{
    int num = m_pRecordTbl->rowCount();
    for(int i=num; i >= 0 ; i--)
    {
       deleteRow(i);
    }
}

void OperationRecord::slotItemClicked(int row, int column)
{
    Q_UNUSED(column)
    // 记录下最近一次的选中的行数
    m_iRow = row;

    QStringList strList;
    strList.clear();
    for(int i=0; i<m_strHeadNameList.size(); i++)
    {
        strList << m_pRecordTbl->item(row,i)->text();
    }
    emit sigItemClicked(strList);
}

// 增删改查界面
RecordInterface::RecordInterface(bool isInner, QWidget * parent) : QWidget(parent)
{
   m_bIsInner = isInner;
   createWin();
   setConnect();
}

void RecordInterface::createWin()
{
    m_pSelectBtn       = new QPushButton("查询");
    m_pAddBtn          = new QPushButton("添加");
    m_pDeleteBtn       = new QPushButton("删除");
    m_pModifyBtn       = new QPushButton("修改");
    m_pClearBtn        = new QPushButton("重置");
    m_pDeleteBtn->setEnabled(false);
    m_pModifyBtn->setEnabled(false);

    QLabel *plate      = new QLabel("    车牌:");
    m_pPlateEdit       = new QLineEdit;
    QLabel *ownner     = new QLabel("车主姓名:");
    m_pOwnnerEdit      = new QLineEdit;
    QLabel *ownnerTel  = new QLabel("联系方式:");
    m_pOwnnerTelEdit   = new QLineEdit;
    QLabel *startime   = new QLabel("开始时间:");
    m_pStartTime       = new QDateEdit;
    m_pStartTime->setDate(QDate::currentDate());
    QLabel *endtime    = new QLabel("结束时间:");
    m_pEndTime         = new QDateEdit;
    m_pEndTime->setDate(QDate::currentDate());
 //    QLineEdit   *m_pOperateTime;
    QLabel *money      = new QLabel("缴费金额:");
    m_pChargeMoneyEdit = new QLineEdit;



    QHBoxLayout *m_pHBL1 = new QHBoxLayout;
    m_pHBL1->addWidget(m_pClearBtn);
    m_pHBL1->addWidget(m_pAddBtn);
    m_pHBL1->addWidget(m_pDeleteBtn);
    m_pHBL1->addWidget(m_pSelectBtn);
    m_pHBL1->addWidget(m_pModifyBtn);


    QHBoxLayout *m_pHBL2 = new QHBoxLayout;
    m_pHBL2->addWidget(plate);
    m_pHBL2->addWidget(m_pPlateEdit);
    QHBoxLayout *m_pHBL3 = new QHBoxLayout;
    m_pHBL3->addWidget(ownner);
    m_pHBL3->addWidget(m_pOwnnerEdit);
    QHBoxLayout *m_pHBL4 = new QHBoxLayout;
    m_pHBL4->addLayout(m_pHBL2);
    m_pHBL4->addLayout(m_pHBL3);

    QHBoxLayout *m_pHBL5 = new QHBoxLayout;
    m_pHBL5->addWidget(startime);
    m_pHBL5->addWidget(m_pStartTime);
    QHBoxLayout *m_pHBL6 = new QHBoxLayout;
    m_pHBL6->addWidget(endtime);
    m_pHBL6->addWidget(m_pEndTime);
    QHBoxLayout *m_pHBL7 = new QHBoxLayout;
    m_pHBL7->addLayout(m_pHBL5);
    m_pHBL7->addLayout(m_pHBL6);

    QHBoxLayout *m_pHBL8 = new QHBoxLayout;
    m_pHBL8->addWidget(ownnerTel);
    m_pHBL8->addWidget(m_pOwnnerTelEdit);
    QHBoxLayout *m_pHBL9 = new QHBoxLayout;
    m_pHBL9->addWidget(money);
    m_pHBL9->addWidget(m_pChargeMoneyEdit);
    QHBoxLayout *m_pHBL10 = new QHBoxLayout;
    m_pHBL10->addLayout(m_pHBL8);
    if(!m_bIsInner)
    {
        m_pHBL10->addLayout(m_pHBL9);
    }

    QVBoxLayout *m_pVBL1  = new QVBoxLayout;
    m_pVBL1->addLayout(m_pHBL1);
    m_pVBL1->addLayout(m_pHBL4);
    m_pVBL1->addLayout(m_pHBL7);
    m_pVBL1->addLayout(m_pHBL10);

    this->setLayout(m_pVBL1);
}

void RecordInterface::setConnect()
{
    connect(m_pSelectBtn, SIGNAL(clicked()),this, SLOT(slotSelect()));
    connect(m_pAddBtn,    SIGNAL(clicked()),this, SLOT(slotAdd()));
    connect(m_pDeleteBtn, SIGNAL(clicked()),this, SLOT(slotDelete()));
    connect(m_pModifyBtn, SIGNAL(clicked()),this, SLOT(slotModify()));
    connect(m_pClearBtn,  SIGNAL(clicked()),this, SLOT(slotClear()));
    connect(DataHandle::getInstance(),SIGNAL(sigMsg(QString)),this,SIGNAL(sigMsg(QString)));
}

void RecordInterface::clearEdit()
{
    m_pPlateEdit->clear();
    m_pOwnnerEdit->clear();
    m_pOwnnerTelEdit->clear();
    m_pChargeMoneyEdit->clear();
}

void RecordInterface::slotSelect()
{
    QString plate  = m_pPlateEdit->text();
    QString ownner = m_pOwnnerEdit->text();

    // 验证信息完整性
    QString strErr;
    MonthAndInnerCardInfo info;
    info.veh_plate = plate;
    info.veh_ownner = ownner;
    if(!DataAuth::getInstance()->authInfoIntegriy(strErr,FEATURE::SELECT,info))
    {
        qDebug() << strErr;
        return;
    }
    emit sigRecordClear();
    if(m_bIsInner)
    {
        QSqlQuery rtnResult;
        if(DataHandle::getInstance()->SelectOfCardVehRecord(rtnResult,plate,ownner))
        {
            while(rtnResult.next())
            {
//                 strList << "车牌号" << "车主姓名" << "联系方式" << "开始时间" << "结束时间" << "办理时间";
                QStringList strList;
                for(int i = 1; i < 7; i++ )
                {
                    strList.push_back(rtnResult.value(i).toString());
                }
                emit sigRecordSelect(strList);
                strList.clear();
                qDebug() << "查询期卡信息" <<strList;
                emit sigMsg("查询期卡信息");
            }
        }
    }
    else
    {
        QSqlQuery rtnResult;
        if(DataHandle::getInstance()->SelectMonthVehRecord(rtnResult,plate,ownner))
        {
            while(rtnResult.next())
            {
//                 strList << "车牌号" << "车主姓名" << "联系方式" << "开始时间" << "结束时间" << "办理时间" <<"费用";
                QStringList strList;
                for(int i = 1; i < 8; i++ )
                {
                       strList.push_back(rtnResult.value(i).toString());
                }
                emit sigRecordSelect(strList);
                strList.clear();
                qDebug() << "查询月卡信息" <<strList;
                emit sigMsg("查询月卡信息");
            }
        }
        else
        {
            qDebug() << "月卡查询失败";
            emit sigMsg("月卡查询失败");
        }
    }
}

void RecordInterface::slotAdd()
{
      MonthAndInnerCardInfo info;
      info.operator_name = "李四";
      info.veh_plate     = m_pPlateEdit->text().trimmed();
      info.veh_ownner    = m_pOwnnerEdit->text().trimmed();
      info.veh_ownner_tel = m_pOwnnerTelEdit->text().trimmed();
      info.veh_valid_start_time = m_pStartTime->text();
      info.veh_valid_end_time   = m_pEndTime->text();
      info.veh_operate_time     = QDate::currentDate().toString("yyyy/MM/dd");

      QString strErr;
      if(!DataAuth::getInstance()->authInfoIntegriy(strErr,FEATURE::ADD,info))
      {
          qDebug () << strErr;
          emit sigMsg(strErr);
          return;
      }

      if(m_bIsInner)
      {
          if(DataHandle::getInstance()->AddOfCardVehRecord(info))
          {
              //strList << "车牌号" << "车主姓名" << "联系方式" << "开始时间" << "结束时间" << "办理时间";
              qDebug()<<"添加期卡信息成功";
              emit sigMsg("添加期卡信息成功");
              QStringList strList;
              strList << info.veh_plate<<info.veh_ownner<<info.veh_ownner_tel
                      <<info.veh_valid_start_time << info.veh_valid_end_time << info.veh_operate_time;
              emit sigRecordAdd(strList);
          }
          else{
              qDebug()<<"添加期卡信息失败";
              emit sigMsg("添加期卡信息失败");
          }
      }
      else
      {
          info.veh_vip_charge_money = m_pChargeMoneyEdit->text().trimmed();
          if(DataHandle::getInstance()->AddMonthVehRecord(info))
          {
              QStringList strList;
              strList << info.veh_plate<<info.veh_ownner<<info.veh_ownner_tel
                      <<info.veh_valid_start_time << info.veh_valid_end_time << info.veh_operate_time
                      << info.veh_vip_charge_money;
              emit sigRecordAdd(strList);
              qDebug()<<"添加期卡信息成功";
              emit sigMsg("添加期卡信息成功");
          }
          else{
              qDebug()<<"添加期卡信息失败";
              emit sigMsg("添加期卡信息失败");
          }
      }
}

void RecordInterface::slotDelete()
{
    clearEdit();
    QString plate  = m_pPlateEdit->text();
    QString ownner = m_pOwnnerEdit->text();

    QString strErr;
    MonthAndInnerCardInfo info;
    info.veh_plate = plate;
    info.veh_ownner = ownner;
    if(!DataAuth::getInstance()->authInfoIntegriy(strErr,FEATURE::DELETE,info))
    {
        qDebug () << strErr;
        return;
    }

    if(m_bIsInner)
    {
        if(DataHandle::getInstance()->DeleteOfCardVehRecord(plate,ownner))
        {
            emit sigRecordDelete(plate,ownner);
            qDebug()<<"删除期卡信息成功";
            emit sigMsg("删除期卡信息成功");
        }
        else
        {
            qDebug()<<"删除期卡信息失败";
            emit sigMsg("删除期卡信息失败");
        }
    }
    else
    {
        if(DataHandle::getInstance()->DeleteMonthVehRecord(plate,ownner))
        {
            emit sigRecordDelete(plate,ownner);
            qDebug()<<"删除月卡信息成功";
            emit sigMsg("删除月卡信息成功");
        }
        else
        {
            qDebug() << "删除月卡信息失败";
            emit sigMsg("删除月卡信息失败");
        }
    }
}

void RecordInterface::slotModify()
{
    MonthAndInnerCardInfo info;
    info.operator_name = "李四";
    info.veh_plate     = m_pPlateEdit->text().trimmed();
    info.veh_ownner    = m_pOwnnerEdit->text().trimmed();
    info.veh_ownner_tel = m_pOwnnerTelEdit->text().trimmed();
    info.veh_valid_start_time = m_pStartTime->text();
    info.veh_valid_end_time   = m_pEndTime->text();
    info.veh_operate_time     = QDate::currentDate().toString("yyyy/MM/dd");

    QString strErr;
    if(!DataAuth::getInstance()->authInfoIntegriy(strErr,FEATURE::MODIFY,info))
    {
        qDebug () << strErr;
        return;
    }

    if(m_bIsInner)
    {
        info.veh_vip_charge_money = m_pChargeMoneyEdit->text().trimmed();
        if(DataHandle::getInstance()->ModifyOfCardVehRecord(info))
        {
            QStringList strList;
            strList << info.veh_plate<<info.veh_ownner<<info.veh_ownner_tel
                    <<info.veh_valid_start_time << info.veh_valid_end_time << info.veh_operate_time;
            qDebug() << strList;
            emit sigRecordModify(strList);
        }
        else{
            qDebug()<<"修改期卡信息失败";
            emit sigMsg("修改期卡信息失败");
        }
    }
    else
    {
        info.veh_vip_charge_money = m_pChargeMoneyEdit->text().trimmed();
        if(DataHandle::getInstance()->ModifyMonthVehRecord(info))
        {
            QStringList strList;
            strList << info.veh_plate<<info.veh_ownner<<info.veh_ownner_tel
                    <<info.veh_valid_start_time << info.veh_valid_end_time << info.veh_operate_time
                    << info.veh_vip_charge_money;
            emit sigRecordModify(strList);
            qDebug()<<"修改月卡信息成功";
            emit sigMsg("修改月卡信息成功");
        }
        else{
            qDebug()<<"修改月卡信息失败";
            emit sigMsg("修改月卡信息失败");
        }
    }
}

void RecordInterface::slotClear()
{
    clearEdit();
    modifyShow(true);
    m_pStartTime->setDate(QDate::currentDate());
    m_pEndTime->setDate(QDate::currentDate());
}

void RecordInterface::slotItemClicked(QStringList strList)
{
    modifyShow(false);
    m_pPlateEdit     -> setText(strList.at(0));
    m_pOwnnerEdit    -> setText(strList.at(1));
    m_pOwnnerTelEdit -> setText(strList.at(2));
    m_pStartTime     -> setDate(QDate::fromString(strList.at(3),"yyyy/MM/dd"));
    m_pEndTime       -> setDate(QDate::fromString(strList.at(4),"yyyy/MM/dd"));
    if(!m_bIsInner)
    {
       m_pChargeMoneyEdit ->setText(strList.at(6));
    }
}

void RecordInterface::modifyShow(bool isShow)
{
    m_pPlateEdit->setEnabled(isShow);
    m_pOwnnerEdit->setEnabled(isShow);
    m_pModifyBtn->setEnabled(!isShow);
    m_pDeleteBtn->setEnabled(!isShow);
}

// 期卡管理
InnerFileManage::InnerFileManage(QWidget *parent) : QWidget(parent)
{
    createWin();
    setConnection();
}

void InnerFileManage::createWin()
{
    QStringList strList;
    strList << "车牌号" << "车主姓名" << "联系方式" << "开始时间" << "结束时间" << "办理时间";
    m_pInnerInterface = new RecordInterface(true);
    m_pInnerRecord    = new OperationRecord(strList);

    QVBoxLayout  *m_pVBL1 = new QVBoxLayout;
    m_pVBL1->addWidget(m_pInnerInterface);
    m_pVBL1->addWidget(m_pInnerRecord);
    this->setLayout(m_pVBL1);
}

void InnerFileManage::setConnection()
{
    connect(m_pInnerRecord,SIGNAL(sigItemClicked(QStringList)),m_pInnerInterface,SLOT(slotItemClicked(QStringList)));
    connect(m_pInnerInterface,SIGNAL(sigRecordSelect(QStringList)),m_pInnerRecord,SLOT(slotAddOneRow(QStringList)));
    connect(m_pInnerInterface,SIGNAL(sigRecordAdd(QStringList)),m_pInnerRecord,SLOT(slotAddOneRow(QStringList)));
    connect(m_pInnerInterface,SIGNAL(sigRecordDelete(QString,QString)),m_pInnerRecord,SLOT(slotDelOneRow(QString,QString)));
    connect(m_pInnerInterface,SIGNAL(sigRecordModify(QStringList)),m_pInnerRecord,SLOT(slotModifyOneRow(QStringList)));
    connect(m_pInnerInterface,SIGNAL(sigRecordClear()),m_pInnerRecord,SLOT(slotClearAllRow()));
    connect(m_pInnerInterface,SIGNAL(sigMsg(QString)),this,SIGNAL(sigMsg(QString)));
}

// 月卡管理
MonthFileManage::MonthFileManage(QWidget *parent) : QWidget(parent)
{
    createWin();
    setConnection();
}

void MonthFileManage::createWin()
{
    QStringList strList;
    strList.clear();
    strList << "车牌号" << "车主姓名" << "联系方式" << "开始时间" << "结束时间" << "办理时间" <<"费用";
    m_pMonthInterface = new RecordInterface(false);
    m_pMonthRecord    = new OperationRecord(strList);

    QVBoxLayout  *m_pVBL2 = new QVBoxLayout;
    m_pVBL2->addWidget(m_pMonthInterface);
    m_pVBL2->addWidget(m_pMonthRecord);
    this->setLayout(m_pVBL2);
}

void MonthFileManage::setConnection()
{
    connect(m_pMonthRecord,SIGNAL(sigItemClicked(QStringList)),m_pMonthInterface,SLOT(slotItemClicked(QStringList)));
    connect(m_pMonthInterface,SIGNAL(sigRecordSelect(QStringList)),m_pMonthRecord,SLOT(slotAddOneRow(QStringList)));
    connect(m_pMonthInterface,SIGNAL(sigRecordAdd(QStringList)),m_pMonthRecord,SLOT(slotAddOneRow(QStringList)));
    connect(m_pMonthInterface,SIGNAL(sigRecordDelete(QString,QString)),m_pMonthRecord,SLOT(slotDelOneRow(QString,QString)));
    connect(m_pMonthInterface,SIGNAL(sigRecordModify(QStringList)),m_pMonthRecord,SLOT(slotModifyOneRow(QStringList)));
    connect(m_pMonthInterface,SIGNAL(sigRecordClear()),m_pMonthRecord,SLOT(slotClearAllRow()));
    connect(m_pMonthInterface,SIGNAL(sigMsg(QString)),this,SIGNAL(sigMsg(QString)));
}
